/*
 * @Author: your name
 * @Date: 2021-12-17 15:31:19
 * @LastEditTime: 2022-05-18 16:30:07
 * @LastEditors: 陈宇 975155172@qq.com
 * @Description: 接口方法 （增 删 改 查）
 * @FilePath: \blog-api\src\user\user.service.ts
 */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Like } from 'typeorm';
import { CategoriesDto, AddCategoriesPostDto, RemoveCategoriesPostDto, QueryCategoriesDto, CreatePostDto } from './dto/create-post.dot';
import { Categories } from './entities/categories.entity';

@Injectable()
export class CategoriesService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(Categories)
    private readonly categoriesRepository: Repository<Categories>,
  ) {}
  
  // 获取分类列表
  async list(body): Promise<CategoriesDto> {
    let categoriesList: any;
    let tagsTotal: number;
    const limit:any = {}
    if (body.page_count) {
      limit.take = body.page_count;
      limit.skip = (body.page - 1) * body.page_count;
    }
    [ categoriesList, tagsTotal ] = await this.categoriesRepository.findAndCount({
      ...limit,
      where: {
        id: body.id,
        categories_name: Like(`%${ body.name ? body.name : '' }%`)
      }
    })
    return {
      list: categoriesList,
      total: Number(tagsTotal),
      page: body.page,
      pageCount: Math.ceil(Number(tagsTotal) / body.page_count),
      pageSize: body.page_count
    };
  }

  // 添加 / 修改 分类
  async addEditorCategories(body: AddCategoriesPostDto): Promise<any> {
    if(body.id) {
      await this.categoriesRepository.update(body.id, {
        categories_name: body.name,
        describe: body.describe
      });
    } else {
      const tag = await this.categoriesRepository.create({
        categories_name: body.name,
        describe: body.describe
      });
      await this.categoriesRepository.save(tag);
    }

    return {}
  }

  // 查询指定分类
  async queryCategories(body: QueryCategoriesDto): Promise<any> {
    const result = await this.categoriesRepository.findBy({
      id: In(body.ids)
    })

    return result;
  }

  // 分类下文章数量添加
  async addAbstractNum(body: QueryCategoriesDto): Promise<any> {
    const result = await this.queryCategories(body);

    return Promise.all(
      result.map(category => {
        category.abstract_num++;
        return this.categoriesRepository.save(category);
      }),
    );
  }

  // 分类下文章数量减少
  async reduceAbstractNum(body: QueryCategoriesDto): Promise<any> {
    const result = await this.queryCategories(body);

    return Promise.all(
      result.map(category => {
        category.abstract_num--;
        return this.categoriesRepository.save(category);
      }),
    );
  }

  // 删除 分类
  async removeCategories(body: RemoveCategoriesPostDto): Promise<any> {
    await this.categoriesRepository.delete(body.id);
    return {}
  }
}
